package huixue.cn.com.rxapp.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import huixue.cn.com.library.util.PixelUtils;

/**
 * Created by gongdongyang 2019/7/18
 * Describe:
 */
public class BufferView extends View {

    private Paint mPaint;

    private int mCenterPointX,mCenterPointY;

    private List<Point> mPoints;

    private Canvas mBufferCanvas;
    private Bitmap mBufferBitmap;


    public BufferView(Context context) {
        this(context,null);
    }

    public BufferView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public BufferView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(Color.BLACK);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setStrokeWidth(PixelUtils.dp2px(5));

        mPoints = new ArrayList<>();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        /*canvas.drawRect(20,20,mCenterPointX,mCenterPointY,mPaint);

        try {
            TimeUnit.MILLISECONDS.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        canvas.drawCircle(mCenterPointX,mCenterPointY,100,mPaint);*/

        /*for (Point p : mPoints) {
            canvas.drawCircle(p.x,p.y,50,mPaint);
        }*/
        if(mBufferBitmap==null){
            //mBufferBitmap = Bitmap.createBitmap(getWidth(),getHeight(), Bitmap.Config.ARGB_8888);
            return;
        }
        canvas.drawBitmap(mBufferBitmap,0,0,null);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        switch (action){
            case MotionEvent.ACTION_DOWN:
                if(mBufferCanvas==null){
                    mBufferBitmap = Bitmap.createBitmap(getWidth(),getHeight(), Bitmap.Config.ARGB_8888);
                    mBufferCanvas = new Canvas(mBufferBitmap);
                }
                mBufferCanvas.drawCircle((int)event.getX(),(int)event.getY(),100,mPaint);
                //mPoints.add(new Point((int)event.getX(),(int)event.getY()));

                break;
            case MotionEvent.ACTION_UP:
                invalidate();
                break;
        }
        return true;

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        mCenterPointX = w/2;
        mCenterPointY = h/2;
    }
}
